package com.ihr360.payroll.service.staff.convertor;

import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.model.ISingleConvertor;
import com.ihr360.payroll.calc.StaffSalaryCalcPeriod;
import com.ihr360.payroll.calc.StaffSalaryCalcPeriodTerm;
import com.ihr360.payroll.model.dto.staff.StaffSalaryProfile;
import com.ihr360.payroll.model.dto.staff.embeddable.SalaryProfileItemsWrapper;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class StaffPayRollInfoList2StaffSalaryCalcPeriodConvertor implements ISingleConvertor<Map<String, List<StaffSalaryProfile>>, Map<String, StaffSalaryCalcPeriod>> {
    @Override
    public Map<String, StaffSalaryCalcPeriod> convertTo(Map<String, List<StaffSalaryProfile>> input) {
        Map<String, StaffSalaryCalcPeriod> staffSalaryCalcPeriodMap = new HashMap<>(input.size());
        for (Map.Entry<String, List<StaffSalaryProfile>> entry : input.entrySet()) {
            String staffId = entry.getKey();
            List<StaffSalaryProfile> infos = entry.getValue();
            if (CollectionUtils.isEmpty(infos)) {
                staffSalaryCalcPeriodMap.put(staffId, null);
                continue;
            }
            StaffSalaryCalcPeriod period = new StaffSalaryCalcPeriod(staffId, null);
            List<StaffSalaryCalcPeriodTerm> terms = infos.stream().filter(s -> s.getSalaryProfile() != null).map(s -> {
                StaffSalaryCalcPeriodTerm term = new StaffSalaryCalcPeriodTerm();
                term.setStartOn(s.getSalaryProfile().getEffectiveAt());
                term.setEndOn(s.getSalaryProfile().getInValidAt());
                SalaryProfileItemsWrapper wrapper = s.getSalaryProfile().getWrapper();
                if (wrapper != null) {
                    term.setItems(wrapper.getItems());
                }
                return term;
            }).collect(Collectors.toList());
            terms.sort((s1, s2) -> s2.getStartOn().compareTo(s1.getStartOn()));
            period.setPhases(terms);
            staffSalaryCalcPeriodMap.put(staffId, period);
        }
        return staffSalaryCalcPeriodMap;
    }
}